package com.hkj.configcenter.core.processor;

import com.hkj.configcenter.core.Context;
import com.hkj.configcenter.core.model.ProjectConfig;
import com.hkj.configcenter.core.utils.PropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;

import java.util.Map;

@Slf4j
public class ConfigBeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {

    private Processor processor;

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        initConfig();

        if (Context.isSwitchOn()) {
            post();
        }

    }

    private synchronized void post() {
        if (processor == null && Context.getZkUrl() != null) {
            if (Context.zkClient == null) {
                processor = new ZkProcessor();
                processor.processorResourceConfig();
                processor.processorFieldConfig();
            }
        }
    }

    private synchronized void initConfig() {

        // 重复初始化校验
        if (Context.getConfig() != null) {
            return;
        }

        // 初始化配置中心配置信息
        try {
            Map<String, String> map = PropertiesUtils.getPropsMap("/conf/project.properties");
            ProjectConfig config = new ProjectConfig();
            config.setRoot(map.get("config.root") != null ? map.get("config.root") : "/config");
            config.setEnv(map.get("config.env") == null ? "/dev" : "/" + map.get("config.env"));
            config.setCommonConfig(map.get("config.commonConfig") != null ? map.get("config.commonConfig") : "/common-config");
            config.setFieldConfig(map.get("config.fieldConfig") != null ? map.get("config.fieldConfig") : "/fieldConfig");
            config.setResourceConfig(map.get("config.resourceConfig") != null ? map.get("config.resourceConfig") : "/resourceConfig");
            config.setZkUrl(map.get("config.zkUrl"));

            String configName = map.get("config.name");
            config.setName(configName.indexOf("/") == 0 ? configName : "/" + configName);
            Context.setConfig(config);
            Context.setSwitchOn(true);
            log.info("【配置中心】 - config = {}", Context.getConfig());
        } catch (Throwable e) {
            e.printStackTrace();
            log.info("【配置中心】【不开启】 - 异常读取文件 ==> /conf/project.properties");
        }
    }

    // 销毁
    public void destory() {
        processor.destroy();
        log.info("【配置中心】 - 关闭配置中心资源成功");
    }

}
